
package com.zjff.myshop.front.controller;

import cn.hutool.core.util.StrUtil;
import com.github.xiaoymin.knife4j.annotations.ApiOperationSupport;
import com.zjff.myshop.entity.Goods;
import com.zjff.myshop.exception.BusinessException;
import com.zjff.myshop.front.pojo.form.GoodsQueryPageForm;
import com.zjff.myshop.front.pojo.vo.GoodsDetailVO;
import com.zjff.myshop.front.pojo.vo.GoodsVO;
import com.zjff.myshop.front.service.GoodsService;
import com.zjff.myshop.util.BeanUtils;
import com.zjff.myshop.util.PageList;
import com.zjff.myshop.util.PageQuery;
import com.zjff.myshop.util.Result;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.validation.Valid;
import java.util.Map;

@CrossOrigin
@RestController
@Api(value = "v1", tags = "04.商品模块")
@RequestMapping("/app/v1/goods")
public class GoodsController {
    private static final Logger logger = LoggerFactory.getLogger(GoodsController.class);
    @Resource
    protected GoodsService goodsService;

    /**
     * 查询商品详情 ById
     */
    @ApiOperationSupport(order = 30)
    @ApiOperation(value = "查询商品详情", notes = "传参为商品id")
    @GetMapping("/{id}")
    public Result<GoodsDetailVO> goodsDetail(@PathVariable @ApiParam(value = "商品id", required = true) Integer id) {
        logger.info("goods detail api,goodsId={}", id);
        //商品是否存在
        Goods goods = goodsService.selectByPrimaryKey(id);
        if (goods == null) {
            throw new BusinessException("商品不存在");
        }

        GoodsDetailVO goodsDetailVO = new GoodsDetailVO();
        BeanUtils.copyProperties(goods, goodsDetailVO);

        //转换商品轮播图数据格式
        String album = goods.getAlbum();
        if (StrUtil.isNotBlank(album)) {
            //以竖线为分隔符，则split的时候需要加上两个斜杠【\\】进行转义
            String[] albums = album.split("\\|");
            goodsDetailVO.setAlbum(albums);
        } else {
            goodsDetailVO.setAlbum(null);
        }
        return Result.ok(goodsDetailVO);
    }

    /**
     * 查询商品分页列表
     */
    @ApiOperationSupport(order = 31)
    @ApiOperation(value = "查询商品分页列表", notes = "根据参数查询返回商品分页列表")
    @ApiImplicitParam(name = "form", value = "商品查询分页参数", dataType = "GoodsQueryPageForm", required = true)
    @PostMapping("/queryPage")
    public Result<PageList<GoodsVO>> queryPage(@Valid @RequestBody GoodsQueryPageForm form) {
        //form参数有： page、limit、categoryId、keyword、status、orderBy
        Map<String, Object> map = BeanUtils.beanToMap(form);
        //封装分页请求参数
        PageQuery pageQuery = new PageQuery(map);
        return Result.ok(goodsService.selectVoPage(pageQuery));
    }
}
